<?php

namespace Beerus\Modules\GoodsTest\Controllers;

use App\Http\Controllers\Controller;
use Biz\model\brand\Brand;
use Biz\model\GoodsTestActivity\FineGoodsModel;
use Biz\service\GoodsTestActivity\FineGoodsService;
use Biz\service\GoodsTestActivity\PackageService;
use Doraemon\tools\ImgUrl;
use Doraemon\tools\Log;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Layout\Content;
use Encore\Admin\Widgets\Form;
use Encore\Admin\Widgets\Tab;
use Exception;
use Illuminate\Contracts\Foundation\Application;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Routing\Redirector;
use Illuminate\Support\MessageBag;

class DetailController extends Controller
{
    const PAGE_SIZE = 20;

    /**
     * 详情页
     * @param \Illuminate\Http\Request $request
     * @param Content $content
     * @param $id
     * @return Content|Application|RedirectResponse|Redirector
     */
    public function index(Request $request, Content $content, $id)
    {
        $data = FineGoodsModel::first(['id' => $id]);
        $activityTitle = $data['activity_title'];
        $type = $data['type'];
        //处理图片id
        $data['advantage_img_id'] = implode(',', $data['advantage_img_id']);

        //处理文案数据
        $textRes = [];
        $text = [];
        foreach ($data['advantage_text'] as $v) {
            $text['advantage_text'] = $v;
            $textRes[] = $text;
        }
        $data['advantage_text'] = $textRes;

        //处理 特殊活动说明
        $descTextRes = [];
        foreach ($data['desc_text'] as $v) {
            $text['desc_text'] = $v;
            $descTextRes[] = $text;
        }
        $data['desc_text'] = $descTextRes;
        //处理组合套餐数据
        $i = 1;
        foreach ($data['package_combination_data'] as $v) {
            $data['package_combination_' . $i] = $v['package'];
            $data['package_combination_goods_num_' . $i] = $v['goods_num'];
            $i++;
        }
        //显示套餐剩余次数
        $packageCountMap = array_column(PackageService::getPackageList($data['brand_id']), 'remaining_times', 'package');
        $packageData = [];
        foreach (FineGoodsModel::PACKAGE as $key => $item) {
            $packageData[$key] = $item . '-剩余次数:' . ($packageCountMap[$key] ?? 0);
        }
        //处理优惠券数据
        if ($data['coupon_text']) {
            $data['coupon_type'] = json_decode($data['coupon_text'], true)['type'];
            $data['coupon_link_url'] = json_decode($data['coupon_text'], true)['link'];
        }

        $form = new Form($data);
        $form->disableReset();//去掉重置按钮
        $form->text('activity_title', '活动名称')->required();
        $form->text('basic_title', '参与测评好物名称')->required();
        $form->decimal('goods_worth', '测试商品单价')->required();
        $form->decimal('goods_max_worth', '测试商品最高价')->required();
        $form->select('category_tag_id', '分类标签')->options(FineGoodsModel::CATEGORY_TAG_MAP)->readOnly();
        $form->select('type', '活动类型')->options(FineGoodsModel::TYPE_MAP)->readOnly();
        if ($type < FineGoodsModel::TYPE_EVALUATION) {
            $form->divider('组合套餐');
            $form->hidden('brand_id', 'brand_id');
            //排期中不可更改套餐和数量
            if ($data['activity_state'] == FineGoodsModel::STATE_APPLYING) {
                if (isset($data['package_combination_1'])) {
                    $form->select('package_combination_1', '活动套餐')->options($packageData)->readOnly();
                    $form->text('package_combination_goods_num_1', '商品数量/测评人数')->readonly();
                }
                if (isset($data['package_combination_2'])) {
                    $form->select('package_combination_2', '活动套餐')->options($packageData)->readOnly();
                    $form->text('package_combination_goods_num_2', '商品数量/测评人数')->readonly();
                }
                if (isset($data['package_combination_3'])) {
                    $form->select('package_combination_3', '活动套餐')->options($packageData)->readOnly();
                    $form->text('package_combination_goods_num_3', '商品数量/测评人数')->readonly();
                }

            } else {
                if (isset($data['package_combination_1'])) {
                    $form->select('package_combination_1', '活动套餐')->options($packageData)->required();
                    $form->number('package_combination_goods_num_1', '商品数量/测评人数')->required()->min(1);
                }
                if (isset($data['package_combination_2'])) {
                    $form->select('package_combination_2', '活动套餐')->options($packageData)->required();
                    $form->number('package_combination_goods_num_2', '商品数量/测评人数')->required()->min(1);
                }
                if (isset($data['package_combination_3'])) {
                    $form->select('package_combination_3', '活动套餐')->options($packageData)->required();
                    $form->number('package_combination_goods_num_3', '商品数量/测评人数')->required()->min(1);
                }
            }
            $form->divider();
        } else {
            $form->radio('coupon_type', '优惠券类型')
                ->options(FineGoodsModel::COUPON_LINK_MAP
                )->when(FineGoodsModel::COUPON_LINK_TYPE_TB, function (Form $form) {
                    $form->url('coupon_link_url', '淘宝优惠券链接');
                })->when(FineGoodsModel::COUPON_LINK_TYPE_JD, function (Form $form) {
                    $form->url('coupon_link_url', '京东优惠券链接');
                });
            $form->text('basic_id', 'WIKI ID')->required();
            //展示品牌
            $lists = Brand::getBrandByFilter([], ['brand_name', 'id', 'is_test', 'brand_type']);
            $brandList = [];
            foreach ($lists as $item) {
                $brandList[$item['id']] = $item['brand_name'] . '|品牌id：' . $item['id'] . '|品牌类型：' . Brand::BRAND_TYPE[$item['brand_type']];
            }
            $form->radio('has_brand', '品牌信息')
                ->options([0 => '无', 1 => '有']
                )->when(0, function (Form $form) {
                    $form->text('brand_name', '品牌名称')->help('请输入品牌名称，名称不超过24个字符(12个中文)');
                })->when(1, function (Form $form) use ($brandList) {
                    $form->select('brand_id', '品牌号')->options($brandList);
                })->default($data['brand_id'] > 0 ? 1 : 0);
            $form->number('goods_num', '参与测评人数')->required();
        }
        $form->imgUpload('cover_img', '活动头图', false, [
            'isUpload' => true,
            'isGetUrl' => true,
            'imgType' => ImgUrl::APPTYPE_BIZ,
            'imgSize' => ImgUrl::IMAGE_SIZE_ORI_NPHONE,
        ])->required();
        $form->imgUpload('advantage_img_id', '商品亮点图片', true, [
            'isUpload' => true,
            'isGetUrl' => true,
            'imgType' => ImgUrl::APPTYPE_BIZ,
            'imgSize' => ImgUrl::IMAGE_SIZE_ORI_NPHONE,
        ])->required()->help('注意：商品亮点图片 至少3张，最多5张');
        $form->table('advantage_text', '亮点介绍文案', function ($table) {
            $table->text('advantage_text')->help('最多20字（最少3条、最多5条）');
        })->required();
        $form->table('desc_text', '添加特殊说明', function ($table) {
            $table->text('desc_text')->placeholder('【输入文案，第一条默认为标题，字数无上限】');
        })->required()->help('必传');
        $form->confirm('确定更新吗？', 'edit');
        $form->action('/admin/goodsTest/detail/' . $id . '/save');

        $tab = new Tab();
        $tab->add('活动详情页', $form->render(), true);
        $tab->addLink('获选名单', url("/admin/goodsTest/joinSelected/index/$id"), false);
        $tab->addLink('测评报告管理', url("/admin/goodsTest/reportList/index/$id"), false);
        $tab->addLink('测评报告', url("/admin/goodsTest/detail/report/$id"), false);
        $content->row($tab);

        return $content
            ->header(FineGoodsModel::TYPE_MAP[$data['type']] . " | $activityTitle | 活动详情页")
            ->description(' ')
            ->breadcrumb(['text' => '审核列表', 'url' => '/goodsTest/index'], ['text' => '活动详情页']);
    }

    public function createTestActivity(Content $content): Content
    {
        $lists = Brand::getBrandByFilter([], ['brand_name', 'id', 'is_test', 'brand_type']);
        $brandList = [];
        foreach ($lists as $item) {
            $brandList[$item['id']] = $item['brand_name'] . '|品牌id：' . $item['id'] . '|品牌类型：' . Brand::BRAND_TYPE[$item['brand_type']];
        }
        $form = new Form(['type' => FineGoodsModel::TYPE_EVALUATION]);
        $form->disableReset();//去掉重置按钮
        $form->hidden('type', '活动类型');
        $form->text('activity_title', '请输入活动名称（最多输入12个字）')->required();
        $form->text('basic_id', 'WIKI ID')->required();
        $form->text('basic_title', '参与测评好物名称')->required();
        $form->decimal('goods_worth', '测试商品单价')->required();
        $form->decimal('goods_max_worth', '最高价（非必填）');
        $form->number('goods_num', '参与测评人数')->required();
        $form->imgUpload('cover_img', '活动头图', false, [
            'isUpload' => true,
            'isGetUrl' => true,
            'imgType' => ImgUrl::APPTYPE_BIZ,
            'imgSize' => ImgUrl::IMAGE_SIZE_ORI_NPHONE,
        ])->help('上传测评商品banner图，建议带有场景的商品宣传图。 2.图片尺寸1200*900px，最大不超过2M，支持png、jpg');
        $form->imgUpload('advantage_img_id', '商品亮点图片', true, [
            'isUpload' => true,
            'isGetUrl' => true,
            'imgType' => ImgUrl::APPTYPE_BIZ,
            'imgSize' => ImgUrl::IMAGE_SIZE_ORI_NPHONE,
        ])->help('1.商品亮点图片展示，最少3张，最多支持5张。 2.图片尺寸600*600px，最大不超过2M，支持png、jpg');
        $form->table('advantage_text', '亮点介绍文案（至少3条)', function ($table) {
            $table->text('advantage_text')->help('最多20字（最少3条、最多5条）');
        })->required();
        $form->radio('has_brand', '品牌信息')
            ->options([0 => '无', 1 => '有']
            )->when(0, function (Form $form) {
                $form->text('brand_name', '品牌名称')->help('请输入品牌名称，名称不超过24个字符(12个中文)');
            })->when(1, function (Form $form) use ($brandList) {
                $form->select('brand_id', '品牌号')->options($brandList);
            })->default(0);
        $form->radio('coupon_type', '优惠券类型')
            ->options(FineGoodsModel::COUPON_LINK_MAP
            )->when(FineGoodsModel::COUPON_LINK_TYPE_TB, function (Form $form) {
                $form->url('coupon_link_url', '淘宝优惠券链接');
            })->when(FineGoodsModel::COUPON_LINK_TYPE_JD, function (Form $form) {
                $form->url('coupon_link_url', '京东优惠券链接');
            });
        $form->confirm('确定添加吗？', 'add');
        $form->action('/admin/goodsTest/index/addTestActivityPost');

        $tab = new Tab();
        $tab->add('创建测评活动', $form->render(), true);
        $tab->addLink('活动列表', url("/admin/goodsTest/index"), false);
        $content->row($tab);
        return $content
            ->header("好好测 | 创建测评活动")
            ->description(' ')
            ->breadcrumb(['text' => '审核列表', 'url' => '/goodsTest/index/'], ['text' => '创建测评活动']);
    }

    /**
     * @param \Illuminate\Http\Request $request
     * @param $id
     * @return \Illuminate\Http\RedirectResponse
     * @throws \Exception
     */
    public function save(Request $request, $id): RedirectResponse
    {
        $brand_id = $request->input('brand_id', 0);//品牌id
        $brand_name = $request->input('brand_name', '');//品牌名称
        $activity_title = $request->input('activity_title', '');//活动名称
        $basic_title = $request->input('basic_title', '');//商品名称
        $goods_num = $request->input('goods_num', 0);//商品数量
        $goods_worth = $request->input('goods_worth', 0);//商品单价
        $goods_max_worth = $request->input('goods_max_worth', 0);//好物价值最高价
        $cover_img = $request->input('cover_img', '');//活动主图 只要图片id
        $advantage_img = $request->input('advantage_img_id', '');//商品亮点图片(多张)json 只要图片id
        $advantage_text = $request->input('advantage_text', []);//商品亮点文案，json
        $desc_text = $request->input('desc_text', []);//特殊活动说明，json

        $package_combination_1 = $request->input('package_combination_1', 0);//组合套餐
        $package_combination_2 = $request->input('package_combination_2', 0);//组合套餐
        $package_combination_3 = $request->input('package_combination_3', 0);//组合套餐
        $package_combination_goods_num_1 = $request->input('package_combination_goods_num_1', 0);//组合套餐所选数量
        $package_combination_goods_num_2 = $request->input('package_combination_goods_num_2', 0);//组合套餐所选数量
        $package_combination_goods_num_3 = $request->input('package_combination_goods_num_3', 0);//组合套餐所选数量

        $type = $request->input('type', 0);//活动类型 FineGoodsModel::TYPE_MAP
        $coupon_type = $request->input('coupon_type', 0);//优惠券类型
        $coupon_link_url = $request->input('coupon_link_url', '');//优惠券链接
        $basic_id = $request->input('basic_id', '');
        try {
            if ($advantage_img == '') {
                throw new Exception('亮点图不可为空');
            }
            //处理文案 去掉 _remove_ =1的
            $advantage_text = array_values(array_filter(array_column(array_slice(FineGoodsService::arrayFilterFieldValue($advantage_text,
                '_remove_',
                0), 0, 5), 'advantage_text')));
            $desc_text = array_values(array_filter(array_column(FineGoodsService::arrayFilterFieldValue($desc_text,
                '_remove_',
                0), 'desc_text')));
            $advantage_img = json_encode(array_slice(explode(',', $advantage_img), 0, 5));

            //处理组合套餐数据
            $package_combination_arr = [];
            if ($package_combination_1 > 0) {
                $package_combination_arr[] = ['package' => $package_combination_1, 'goods_num' => $package_combination_goods_num_1];
            }
            if ($package_combination_2 > 0) {
                $package_combination_arr[] = ['package' => $package_combination_2, 'goods_num' => $package_combination_goods_num_2];
            }
            if ($package_combination_3 > 0) {
                $package_combination_arr[] = ['package' => $package_combination_3, 'goods_num' => $package_combination_goods_num_3];
            }
            $package_combination = json_encode($package_combination_arr);

            $coupon_text = '';
            if ($coupon_link_url) {
                $coupon_text = json_encode(['type' => $coupon_type, 'link' => $coupon_link_url]);
            }
            $package_num = $package_combination_goods_num_1 + $package_combination_goods_num_2 + $package_combination_goods_num_3;
            if ($package_num == 0) {
                $package_num = $goods_num;
            }

            if ($package_num == 0) {
                throw new Exception('活动人数为0不可提交');
            }

            $data = [
                'brand_id' => $brand_id,
                'activity_title' => $activity_title,
                'basic_title' => $basic_title,
                'goods_worth' => $goods_worth,
                'goods_max_worth' => $goods_max_worth,
                'goods_num' => $package_num,
                'cover_img' => $cover_img,
                'advantage_img' => $advantage_img,
                'advantage_text' => json_encode($advantage_text),
                'desc_text' => json_encode($desc_text),
                'operate_type' => FineGoodsModel::OPERATE_TYPE_ADMIN,
                'operate_uid' => Admin::user()->id,
                'package_combination' => $package_combination,
            ];
            if ($type == FineGoodsModel::TYPE_EVALUATION) {// 1,2 为轻测或开箱 3为测评
                if ($brand_id > 0) {
                    $brand_name = \Biz\service\brand\Brand::getBrandInfoById($brand_id)['brand_name'] ?? '';
                }
                $data['basic_id'] = $basic_id;
                $data['coupon_text'] = $coupon_text;
                $data['brand_name'] = $brand_name;
            }
            if (!$cover_img) {
                throw new Exception('主图不可为空');
            }
            if (mb_strlen($activity_title, 'utf8') > 12) {
                throw new Exception('活动名称文字不能超过12个');
            }
            if (count($advantage_text) < 3) {
                throw new Exception('亮点介绍至少为3条');
            }

            if ($advantage_text) {
                foreach ($advantage_text as $value) {
                    if (mb_strlen($value, 'utf8') > 20) {
                        throw new Exception('单条亮点文案文字不能超过20个');
                    }
                }
            }
            $result = FineGoodsService::saveData($data, $id);
            if (!$result) {
                throw new Exception('活动编辑失败');
            }

            return redirect('/admin/goodsTest/index');
        } catch (Exception $e) {
            Log::error('活动编辑失败', $e->getMessage());
            $error = new MessageBag([
                'title' => '编辑失败,' . $e->getMessage(),
            ]);

            return back()->with(compact('error'));
        }

    }

    /**
     * 保存测评活动数据-入库操作
     * @param \Illuminate\Http\Request $request
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector|void
     */
    public function addTestActivityPost(Request $request)
    {
        $type = $request->input('type', 0);//活动类型
        $activity_title = $request->input('activity_title', '');//活动名称
        $basic_id = $request->input('basic_id', 0);
        $basic_title = $request->input('basic_title', '');//商品名称
        $goods_worth = $request->input('goods_worth', 0);//商品单价
        $goods_num = $request->input('goods_num', 0);//参与测评人数
        $goods_max_worth = $request->input('goods_max_worth', 0);//好物价值最高价
        $cover_img = $request->input('cover_img', '');//活动主图 只要图片id
        $advantage_img = $request->input('advantage_img_id', '');//商品亮点图片(多张)json 只要图片id
        $advantage_text = $request->input('advantage_text', []);//商品亮点文案，json
        $brand_id = $request->input('brand_id', 0);//品牌id
        $brand_name = $request->input('brand_name', '');//品牌名称
        $coupon_type = $request->input('coupon_type', 0);//优惠券类型
        $coupon_link_url = $request->input('coupon_link_url', '');//优惠券链接

        try {
            if ($advantage_img == '') {
                throw new Exception('亮点图不可为空');
            }
            if ($goods_num == 0) {
                throw new Exception('活动人数为0不可提交');
            }
            //处理文案 去掉 _remove_ =1的
            $advantage_text = array_values(array_filter(array_column(array_slice(FineGoodsService::arrayFilterFieldValue($advantage_text,
                '_remove_',
                0), 0, 5), 'advantage_text')));
            $advantage_img = array_slice(explode(',', $advantage_img), 0, 5);

            if (!$cover_img) {
                throw new Exception('主图不可为空');
            }
            if (mb_strlen($activity_title, 'utf8') > 12) {
                throw new Exception('请输入活动名称（最多输入12个字）');
            }
            if (count($advantage_text) < 3) {
                throw new Exception('亮点介绍至少为3条');
            }
            if (count($advantage_img) < 3) {
                throw new Exception('亮点图片至少为3张');
            }

            if ($advantage_text) {
                foreach ($advantage_text as $value) {
                    if (mb_strlen($value, 'utf8') > 20) {
                        throw new Exception('单条亮点文案文字不能超过20个');
                    }
                }
            }
            $coupon_text = '';
            if ($coupon_link_url) {
                $coupon_text = json_encode(['type' => $coupon_type, 'link' => $coupon_link_url]);
            }
            if ($brand_id > 0) {
                $brand_name = \Biz\service\brand\Brand::getBrandInfoById($brand_id)['brand_name'] ?? '';
            }
            $data = [
                'type' => $type,
                'activity_title' => $activity_title,
                'basic_id' => $basic_id,
                'basic_title' => $basic_title,
                'goods_worth' => $goods_worth,
                'goods_num' => $goods_num,
                'goods_max_worth' => $goods_max_worth,
                'cover_img' => $cover_img,
                'advantage_img' => json_encode($advantage_img),
                'advantage_text' => json_encode($advantage_text),
                'brand_id' => $brand_id,
                'brand_name' => $brand_name,
                'coupon_text' => $coupon_text,
                'activity_state' => FineGoodsModel::STATE_WAIT,
                'operate_type' => FineGoodsModel::OPERATE_TYPE_ADMIN,
                'operate_uid' => Admin::user()->id,
            ];
            $id = FineGoodsModel::insertData($data);
            if (!$id) {
                throw new \Exception('创建测评活动失败');
            }
            return redirect('/admin/goodsTest/index');
        } catch (Exception $e) {
            Log::error('创建测评活动失败', $e->getMessage());
            $error = new MessageBag([
                'title' => '添加失败,' . $e->getMessage(),
            ]);

            return back()->with(compact('error'));
        }

    }
}
